package com.rongshu.view.discovery.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.rongshu.R;
import com.rongshu.eventbus.DiscoverySearchResult;
import com.rongshu.eventbus.SearchResultAuthorState;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.adapter.AuthorListItemAdapter;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.discovery.bean.SearchAuthorResponse;
import com.rongshu.view.discovery.contract.AuthorItemClickListener;
import com.rongshu.view.discovery.contract.SearchAuthorView;
import com.rongshu.view.discovery.presenter.SearchAuthorPresenter;
import com.rongshu.view.home.bean.LabelResponse;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static android.app.Activity.RESULT_OK;

/**
 * created by zhengweis on 2018/11/1.
 * description：展示用户列表
 */
public class SearchResultAuthorFragment extends BaseFragment<SearchAuthorPresenter> implements SearchAuthorView {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.no_data_img)
    ImageView noDataImg;
    @BindView(R.id.no_data_layout)
    RelativeLayout noDataLayout;
    @BindView(R.id.refresh_view)
    SmartRefreshLayout refreshView;

    private AuthorListItemAdapter adapter;
    private List<AuthorDetailBean> articleList;
    private LabelResponse.ResponseBean bean;
    private int pageIndex = 1;
    private int pageSize = 10;
    private String msg;
    private int clickPosition;
    private int REQUEST_CODE = 100;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_search_result_author;
    }


    /**
     * 接受输入框的信息
     *
     * @param data
     */
    @Subscribe
    public void onMessageEventPost(DiscoverySearchResult data) {
        pageIndex = 1;
        msg = data.getMsg();
        presenter.getData(msg, pageIndex, pageSize);
    }

    /**
     * 同步用户 关注/未关注 状态
     *
     * @param data
     */
    @Subscribe
    public void onMessageEventPost(SearchResultAuthorState data) {
        for (AuthorDetailBean bean : articleList) {
            if (bean.getUserid() == data.getAuthorId()) {
                bean.setIsConcern(data.getIsConcern());
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void initViews() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        articleList = new ArrayList<>();
        adapter = new AuthorListItemAdapter(getActivity(), articleList);
        recyclerView.setAdapter(adapter);
        adapter.setAdapterListener(new AuthorItemClickListener() {
            @Override
            public void onItemClickListener(int type, int position) {
                clickPosition = position;
                AuthorDetailBean bean = articleList.get(clickPosition);
                if (type == AuthorItemClickListener.ADD_ATTENTION) {
                    if (bean.getIsConcern() == 1) {
                        presenter.cancelConcernWith(bean.getUserid());
                    } else {
                        presenter.ConcernWith(bean.getUserid());
                    }
                } else if (type == AuthorItemClickListener.INTENT_DETAILS) {
                    if (UserInfoUtils.getUserInfo() == null) {
                        LoginUtils.toLogin(getActivity());
                    } else {
                        Intent intent = new Intent();
                        if (UserInfoUtils.getUserId() == bean.getUserid()) {
                            intent.setClass(getActivity(), PersonDetailsActivity.class);
                            startActivity(intent);
                        } else {
                            intent.setClass(getActivity(), UserHomePageActivity.class);
                            int userid = bean.getUserid();
                            intent.putExtra("UserId", userid);
                            startActivityForResult(intent, REQUEST_CODE);
                        }
                    }
                }
            }
        });

        refreshView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageIndex = 1;
                refreshView.resetNoMoreData();
                presenter.getData(bean.getTitle(), pageIndex, pageSize);
            }
        });
        refreshView.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                pageIndex++;
                presenter.getData(bean.getTitle(), pageIndex, pageSize);
            }
        });
    }

    @Override
    protected void initData() {
        Bundle bundle = getArguments();
        bean = (LabelResponse.ResponseBean) bundle.getSerializable("searchMsg");
        setPresenter(new SearchAuthorPresenter(getActivity()), this);
        if (bean != null) {
            msg = bean.getTitle();
            presenter.getData(msg, pageIndex, pageSize);
        }
    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void success(Object object, int tag) {
        SearchAuthorResponse response = (SearchAuthorResponse) object;
        if (response == null) {
            return;
        }
        if (pageIndex == 1) {
            articleList.clear();
        }
        if (refreshView.isLoading()) {
            refreshView.finishLoadmore();
        }
        if (refreshView.isRefreshing()) {
            refreshView.finishRefresh();
        }
        List<AuthorDetailBean> list = response.getResponse();
        articleList.addAll(list);
        adapter.notifyDataSetChanged();
        noDataLayout.setVisibility(articleList.size() == 0 ? View.VISIBLE : View.GONE);
        if (list.size() < pageSize) {
            refreshView.setLoadmoreFinished(true);
        }
    }

    @Override
    public void faild(Object object, int tag) {
    }

    @Override
    public void concernSuccess() {
        articleList.get(clickPosition).setIsConcern(articleList.get(clickPosition).getIsConcern() == 0 ? 1 : 0);
        adapter.notifyDataSetChanged();
        sendConcernAuthor();
    }

    private void sendConcernAuthor() {
        SearchResultAuthorState state = new SearchResultAuthorState();
        state.setAuthorId(articleList.get(clickPosition).getUserid());
        state.setIsConcern(articleList.get(clickPosition).getIsConcern());
        EventBus.getDefault().post(state);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
            boolean booleanExtra = data.getBooleanExtra(Constant.IS_COLLECT, false);
            articleList.get(clickPosition).setIsConcern(booleanExtra ? 1 : 0);
            adapter.notifyItemChanged(clickPosition);
        }
    }
}
